package com.wuh.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wuh.model.*;
import com.wuh.service.CastleService;
import com.wuh.service.ClassInforService;
import com.wuh.service.GroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
public class GroupController {

    @Autowired
    private GroupService groupService;
    @Autowired
    private ClassInforService classInforService;
    @Autowired
    private CastleService castleService;


    /**
     * 挑战到我的群组界面
     * @return
     */
    @RequestMapping("/toMyGroup")
    public String toMyGroup(HttpSession session,GroupInfo groupInfo) {
        if(session.getAttribute("loginMessage").equals("teacher")){
            Teacher sessUser = (Teacher) session.getAttribute("sess_user");
                groupInfo.setTeacher(sessUser);
                groupInfo.setStatus("0");
        PageInfo<GroupInfo> groups1 = groupService.getGroups(groupInfo);
        session.setAttribute("teacher_group", groups1);
        }
        groupInfo.setStatus("0");
        PageInfo<GroupInfo> groups = groupService.getGroups(groupInfo);
        session.setAttribute("my_group", groups);
        return "person/user_group";
    }

    /**
     * 主页群组聊天首页
     * @param session
     * @return
     */
    @RequestMapping("/toGroup")
    public String toGroup(HttpSession session,GroupInfo groupInfo,Integer group_type) {
       if(group_type!=null){
           groupInfo.setGroup_type(group_type);
       }
        groupInfo.setStatus("0");
        List<GroupInfo> groups = groupService.getGroups1(groupInfo);
        System.out.println(groups.size());
       for (GroupInfo g:groups){
           g.setCount(groupService.getCountByGroupId(g.getGroup_id()));
       }

        session.setAttribute("sess_group", groups);
        session.setAttribute("type",group_type);
        return "groupchat/groupmain";
    }

    /**
     * 本地图片保存
     * @param fileDoMain
     * @param image
     * @return
     * @throws FileNotFoundException
     */
    @PostMapping("/uploadImg")
    @ResponseBody
    public String uploadImg(FileDoMain fileDoMain, @RequestParam("image") MultipartFile image) throws FileNotFoundException {
        String fileDirPath = new String("src/main/resources/" + "static/groupheadImg");
        File staticfile =new File(fileDirPath);
        fileDoMain.setmyfile(image);
        String filename = image.getOriginalFilename();
        int lastIndex = filename.lastIndexOf(".");
        String suffix = filename.substring(lastIndex);
        Date date = new Date();
        String newName = date.getTime() + suffix;
        String uploadPath = staticfile.getAbsolutePath()+File.separator+newName;
        String imgPath = "groupheadImg"+"\\"+newName;
        File targetFile = new File(uploadPath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        try {
            fileDoMain.getmyfile().transferTo(targetFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imgPath;
    }

    /**
     * 本地图片保存
     * @param groupInfo
     * @param session
     * @return
     */
    @PostMapping("/createGroup")
    public String  createGroup(GroupInfo groupInfo,HttpSession session){
            groupInfo.setCreate_time(new Date());
            groupInfo.setLast_modify(groupInfo.getCreate_time());
            groupInfo.setStatus("0");
        Teacher sess_user = (Teacher) session.getAttribute("sess_user");
            groupInfo.setTeacher(sess_user);
            groupService.insertGroup(groupInfo);
            return "redirect:/toMyGroup";
    }

    /**
     * 跳转到群组资料
     * @param id
     * @param session
     * @return
     */
    @RequestMapping("toGroupDetails")
    public  String toGroupDetails(Integer id,HttpSession session,GroupUser groupUser){
        GroupInfo groupInfo = groupService.selectGroupById(id);
        int id1 = groupService.getCountByGroupId(id);
        groupInfo.setCount(id1);
        groupUser.setGroup_id(id);

        groupUser.setType("0");
        List<GroupUser> groupUsers = groupService.getGroupUser(groupUser);
         groupUser.setType("1");
        List<GroupUser> groupAdmins = groupService.getGroupUser(groupUser);
        session.setAttribute("sess_groupusers",groupUsers);
        session.setAttribute("sess_groupadmins",groupAdmins);
        session.setAttribute("sess_groupdetail",groupInfo);
        return "groupchat/groupdetails";
    }
    @RequestMapping("/joingroup")
    public String joingroup(Integer id,HttpSession session,GroupUser groupUser){
            User user = (User) session.getAttribute("sess_user");
            if(user ==null){
                return  "redirect:/toLogin";
            }else{
                groupUser.setCreate_time(new Date());
                groupUser.setAdmin_id(user.getUser_id());
                groupUser.setGroup_id(id);
                groupUser.setType("0");
                groupService.insertGroupUser(groupUser);
                return  "redirect:/toGroup";
            }
    }

    /**
     * 跳转到聊天室
     * @param id
     * @return
     */
    @RequestMapping("/tochat")
        public String tochat(Integer id,HttpSession session,GroupUser groupUser){
        GroupInfo groupInfo = groupService.selectGroupById(id);
        groupUser.setGroup_id(id);
        groupUser.setType("0");
        List<GroupUser> groupUser1 = groupService.getGroupUser(groupUser);
        groupUser.setType("1");
        List<GroupUser> groupAmdin = groupService.getGroupUser(groupUser);
        session.setAttribute("sess_groupusers",groupUser1);
        session.setAttribute("sess_groupadmins",groupAmdin);
        session.setAttribute("sess_chatroom", groupInfo);
        return "groupchat/groupchat";
        }

    /**
     * 根据群组id和用户id退出群聊
     * @param gid
     * @param uid
     * @param groupUser
     * @return
     */
        @RequestMapping("/eixtGroup")
        public  String  exitGroup(Integer gid,Integer uid,GroupUser groupUser){
                groupUser.setGroup_id(gid);
                groupUser.setAdmin_id(uid);
                groupService.deleteGroupUser(groupUser);
                return "redirect:/toGroup";
        }

    /**
     * 解散群 设置status 为 1 表示关闭
     * @param gid
     * @param classInfor
     * @param castleInfo
     * @return
     */
        @RequestMapping("/destoryGroup")
        public String destoryGroup(Integer gid,GroupUser groupUser,ClassInfor classInfor,CastleInfo castleInfo){
                groupUser.setGroup_id(gid);
                groupService.deleteGroupInfo(gid);
               groupService.deleteGroupUser(groupUser);
            List<Integer> classIdByGroup = classInforService.getClassIdByGroup(gid);
            List<Integer> castleIdByGroup = castleService.getCastleIdByGroup(gid);
            castleInfo.setGroup_id(null);
            classInfor.setGroupId(null);
            for (int i =0;i<classIdByGroup.size();i++){
                        classInfor.setClassId(classIdByGroup.get(i));
                        classInforService.updateGroupId(classInfor);
            }
            for (int i =0;i<castleIdByGroup.size();i++){
                castleInfo.setCastle_id(castleIdByGroup.get(i));
                castleService.updatecastleId(castleInfo);
            }
            return  "redirect:/toGroup";
        }

    /**
     * 推出群2
     * @param gid
     * @param uid
     * @param groupUser
     * @return
     */
    @RequestMapping("/eixtGroup1")
    public  String  exitGroup1(Integer gid,Integer uid,GroupUser groupUser){
        groupUser.setGroup_id(gid);
        groupUser.setAdmin_id(uid);
        groupService.deleteGroupUser(groupUser);
        return "redirect:/toMyGroup";
    }

    /**
     * 提交申请表
     * @param groupAdminApply
     * @return
     */
    @PostMapping("applyAdmin")
    public String applyAdmin(GroupAdminApply groupAdminApply,User user,Integer user_id){
                groupAdminApply.setApply_time(new Date());
                user.setUser_id(user_id);
                groupAdminApply.setUser(user);
                groupAdminApply.setStatus("0");
                groupService.insertApply(groupAdminApply);
                return  "redirect:/toMyGroup";
    }

    /**
     * 解散群2
     * @param gid
     * @param groupUser
     * @param classInfor
     * @param castleInfo
     * @return
     */
    @RequestMapping("/destoryGroup1")
    public String destoryGroup1(Integer gid,GroupUser groupUser,ClassInfor classInfor,CastleInfo castleInfo){
        groupUser.setGroup_id(gid);
        groupService.deleteApply(gid);
        groupService.deleteGroupInfo(gid);
        groupService.deleteGroupUser(groupUser);
        List<Integer> classIdByGroup = classInforService.getClassIdByGroup(gid);
        List<Integer> castleIdByGroup = castleService.getCastleIdByGroup(gid);
        castleInfo.setGroup_id(null);
        classInfor.setGroupId(null);
        for (int i =0;i<classIdByGroup.size();i++){
            classInfor.setClassId(classIdByGroup.get(i));
            classInforService.updateGroupId(classInfor);
        }
        for (int i =0;i<castleIdByGroup.size();i++){
            castleInfo.setCastle_id(castleIdByGroup.get(i));
            castleService.updatecastleId(castleInfo);
        }
        return  "redirect:/toMyGroup";
    }

    /**
     * 前往修改界面
     * @param gid
     * @param model
     * @return
     */
        @RequestMapping("toeditGroup")
        public String toeditGroup(Integer gid, Model model,GroupUser groupUser,GroupAdminApply groupAdminApply){
                GroupInfo groupInfo = groupService.selectGroupById(gid);
                groupInfo.setCount(groupService.getCountByGroupId(gid));
                groupUser.setGroup_id(groupInfo.getGroup_id());
                groupAdminApply.setGroup_id(gid);
                groupAdminApply.setStatus("0");
            List<GroupAdminApply> groupAdminApply1 = groupService.getGroupAdminApply(groupAdminApply);
            model.addAttribute("applyn",groupAdminApply1);
            model.addAttribute("editgroup",groupInfo);
             groupUser.setType("0");
             List<GroupUser> groupUsers = groupService.getGroupUser(groupUser);
             groupUser.setType("1");
             List<GroupUser> groupAdmins = groupService.getGroupUser(groupUser);
             model.addAttribute("groupusers",groupUsers);
             model.addAttribute("groupadmins",groupAdmins);
                return  "groupchat/editgroup";

        }

    /**
     * 修改群信息
     * @param groupInfo
     * @return
     */
    @RequestMapping("editGroup")
      public String editGroup(GroupInfo groupInfo){
            groupInfo.setLast_modify(new Date());
            groupService.updateGroupInfo(groupInfo);
            return "redirect:/toUserIndex";
        }

    /**
     * 删除群人员
     * @param ids
     * @param groupUser
     * @return
     */
        @RequestMapping("deleteGroupUser")
    public  String deleteGroupUser(Integer[] ids,GroupUser groupUser){
            for (Integer id:ids
                 ) {
                groupUser.setGroup_admin_id(id);
                groupService.deleteGroupUser(groupUser);
            }

            return  "redirect:/toUserIndex";
        }

    /**
     * 通过申请
     * @param ids
     * @param tid
     * @param gid
     * @param groupAdminApply
     * @param groupUser
     * @return
     */
        @RequestMapping("passGroupUser")
        public  String passGroupUser(Integer[] ids,Integer tid,Integer gid,GroupAdminApply groupAdminApply,GroupUser groupUser){
                groupAdminApply.setCheck_time(new Date());
                groupAdminApply.setStatus("1");
                groupAdminApply.setCheck_teacher(tid);
                for (Integer id:ids){
                    groupAdminApply.setApply_id(id);
                    groupService.updateGroupAdminApply(groupAdminApply);
                    List<GroupAdminApply> groupAdminApply1 = groupService.getGroupAdminApply(groupAdminApply);
                    groupUser.setGroup_id(gid);
                    groupUser.setType("1");
                    groupUser.setAdmin_id(groupAdminApply1.get(0).getUser().getUser_id());
                    groupService.updateGroupUser(groupUser);
                }
             return  "redirect:/toUserIndex";

        }

    /**
     * 退回申请
     * @param ids
     * @param tid
     * @param gid
     * @param groupAdminApply
     * @param groupUser
     * @return
     */
        @RequestMapping("backGroupUser")
        public  String backGroupUser(Integer[] ids,Integer tid,Integer gid,GroupAdminApply groupAdminApply,GroupUser groupUser){
            groupAdminApply.setCheck_time(new Date());
            groupAdminApply.setStatus("2");
            groupAdminApply.setCheck_teacher(tid);
            for (Integer id:ids){
                groupAdminApply.setApply_id(id);
                groupService.updateGroupAdminApply(groupAdminApply);
            }
            return  "redirect:/toUserIndex";

        }

        @RequestMapping("/togrouplist")
        public  String togrouplist(HttpSession session,GroupUser groupUser,GroupInfo groupInfo){
            groupInfo.setStatus("0");
            PageInfo<GroupInfo> groups = groupService.getGroups(groupInfo);
            groupUser.setType("1");
            for (GroupInfo g:groups.getList()
                 ) {
                groupUser.setGroup_id(g.getGroup_id());
                g.setAdmincount(groupService.getAdminCountByGroupId(groupUser));
                g.setCount(groupService.getCountByGroupId(g.getGroup_id()));
            }
            session.setAttribute("schval", groupInfo);
            session.setAttribute("grouplist", groups);
            return "groupchat/grouplist";
        }

        @RequestMapping("deleteGroups")
    public String deleteGroups(Integer[] ids){
            for (Integer id:ids){
                groupService.deleteGroupInfo(id);
            }
            return "redirect:/togrouplist";
        }
}